package com.lanhao.aot.websocket.config;

import java.net.URI;

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

/**
 * Websocket客户端bean配置
 * 
 * @author kunzhou3
 */
@Component
public class WebSocketConfig {
	private static final Logger LOG = LoggerFactory.getLogger(WebSocketConfig.class);
	@Bean
	public WebSocketClient webSocketClient() {
		try {
			WebSocketClient webSocketClient = new WebSocketClient(new URI("ws://localhost:8085/websocket/test")) {
				@Override
				public void onOpen(ServerHandshake handshakedata) {
					LOG.info("[websocket] 连接成功");
				}
				@Override
				public void onMessage(String message) {
					LOG.info("[websocket] 收到消息={}", message);
				}
				@Override
				public void onClose(int code, String reason, boolean remote) {
					LOG.info("[websocket] 退出连接");
				}
				@Override
				public void onError(Exception ex) {
					LOG.info("[websocket] 连接错误={}", ex.getMessage());
				}
			};
			webSocketClient.connect();
			return webSocketClient;
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

}